<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"  />
<title>An Intro to Backbone.js: Part 1 &#8211; Models and Collections - Liquid Media</title>
<meta name="generator" content="WordPress 3.4.2" />
<meta name="robots" content="follow, all" />
<link rel="stylesheet" href="http://liquidmedia.org/wp-content/themes/vulcan/style.css" type="text/css" media="screen" />

<link rel="alternate" type="application/rss+xml" title="Liquid Media RSS Feed" href="http://liquidmedia.org/feed/" />
<link rel="pingback" href="http://liquidmedia.org/xmlrpc.php" />
<script src="http://liquidmedia.org/wp-content/themes/vulcan/js/syntax/shCore.js"></script>
<script src="http://liquidmedia.org/wp-content/themes/vulcan/js/syntax/shBrushJScript.js"></script>
<script src="http://liquidmedia.org/wp-content/themes/vulcan/js/syntax/shBrushXml.js"></script>
<link rel="Stylesheet" type="text/css" href="http://liquidmedia.org/wp-content/themes/vulcan/css/styles/syntax/shCore.css" />
<link rel="Stylesheet" type="text/css" href="http://liquidmedia.org/wp-content/themes/vulcan/css/styles/syntax/shThemeEclipse.css" />
<script src="http://guestlistapp.com/javascripts/guestlist-embed.js"></script>
<link rel="alternate" type="application/rss+xml" title="Liquid Media &raquo; An Intro to Backbone.js: Part 1 &#8211; Models and Collections Comments Feed" href="http://liquidmedia.org/blog/2011/01/backbone-js-part-1/feed/" />
<script type='text/javascript' src='http://liquidmedia.org/wp-includes/js/jquery/jquery.js?ver=1.7.2'></script>
<script type='text/javascript' src='http://liquidmedia.org/wp-content/themes/vulcan/js/jquery.cycle.all.js?ver=3.4.2'></script>
<script type='text/javascript' src='http://liquidmedia.org/wp-content/themes/vulcan/js/jquery.corner.js?ver=3.4.2'></script>
<script type='text/javascript' src='http://liquidmedia.org/wp-content/themes/vulcan/js/jqueryslidemenu.js?ver=3.4.2'></script>
<script type='text/javascript' src='http://liquidmedia.org/wp-content/themes/vulcan/js/jquery.prettyPhoto.js?ver=3.4.2'></script>
<script type='text/javascript' src='http://liquidmedia.org/wp-content/themes/vulcan/js/functions.js?ver=3.4.2'></script>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://liquidmedia.org/xmlrpc.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://liquidmedia.org/wp-includes/wlwmanifest.xml" /> 
<link rel='prev' title='Urtak Facebook App launches' href='http://liquidmedia.org/news/2011/01/urtak-facebook-app-launches/' />
<link rel='next' title='New design coming soon' href='http://liquidmedia.org/blog/2011/01/new-design-coming-soon/' />
<meta name="generator" content="WordPress 3.4.2" />
<link rel='canonical' href='http://liquidmedia.org/blog/2011/01/backbone-js-part-1/' />
<link rel='shortlink' href='http://liquidmedia.org/?p=118' />
	<!--<link rel="stylesheet" href="http://liquidmedia.org/wp-content/themes/vulcan/css/jqueryslidemenu.css" type="text/css" media="screen" />-->
	<link rel="stylesheet" href="http://liquidmedia.org/wp-content/themes/vulcan/css/prettyPhoto.css" type="text/css" media="screen" />
		 <link rel="stylesheet" href="http://liquidmedia.org/wp-content/themes/vulcan/css/styles/default.css" type="text/css" media="screen" />
	<!--[if IE 6]>    
	<link href="http://liquidmedia.org/wp-content/themes/vulcan/css/ie6.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://liquidmedia.org/wp-content/themes/vulcan/js/DD_belatedPNG.js"></script>
	<script type="text/javascript"> 
	   DD_belatedPNG.fix('img'); 
       DD_belatedPNG.fix('#pager a, ul.list-bottom li');
       DD_belatedPNG.fix('#footer-content, .dot-separator');
       DD_belatedPNG.fix('blockquote');   
	</script>    
<![endif]-->
<!--[if IE 7]>    
	<style type="text/css">
    #pager{top:260px;}
    #slideshow ul, #slideshow li{margin:12px 0px 0px 6px;}
    #content .front-box-content{padding-bottom:45px;}
    </style>
<![endif]-->
<!--[if IE 8]>    
	<style type="text/css">
    #pager{top:260px;}
    </style>
<![endif]-->

<!-- ////////////////////////////////// -->
<!-- //      Javascript Files        // -->
<!-- ////////////////////////////////// -->
<script type="text/javascript" src="http://liquidmedia.org/wp-content/themes/vulcan/js/cufon-yui.js"></script>
<script type="text/javascript" src="http://liquidmedia.org/wp-content/themes/vulcan/js/fonts/quicksand.font.js"></script>

</head>
<body>
	<div id="container">
    
    	<!-- BEGIN OF HEADER -->
    	<div id="top-container-inner">
        
        	<!-- begin of logo and mainmenu -->
        	<div id="header">
            	<div id="logo">
              								<a href="http://liquidmedia.org"><img src="http://liquidmedia.org/wp-includes/images/logo.png" alt="Liquid Media" /></a>
              
              </div>
              <div id="mainmenu">
                	<ul class="navigation">
  	<li ><a href="http://liquidmedia.org">Home</a></li>
  	<li class="page_item page-item-2"><a href="http://liquidmedia.org/software_application_developer/">About</a></li>
<li class="page_item page-item-15"><a href="http://liquidmedia.org/portfolio/">Portfolio</a></li>
<li class="page_item page-item-17"><a href="http://liquidmedia.org/contact/">Contact</a></li>
<li class="page_item page-item-81"><a href="http://liquidmedia.org/solutions/">Solutions</a></li>
<li class="page_item page-item-207"><a href="http://liquidmedia.org/blog/">Blog</a></li>
  </ul>

              </div>          
            </div>
            <!-- end of logo and mainmenu -->
            
                        
            <!-- begin of welcome-slogan -->
                        <!-- end of welcome-slogan -->
                    
        </div>
        <!-- END OF HEADER -->
        <!-- BEGIN OF PAGE TITLE -->
        
              
        <div id="page-title">
        	<div id="page-title-inner">
                <div class="title">
                <h1>
                  Blog                
                </h1>
                </div>                
            </div>   	            
        </div>
        <!-- END OF PAGE TITLE --> 
        
        <!-- BEGIN OF CONTENT -->
        <div id="content">
        	<div id="content-left">          
                <div class="maincontent">
                                    <!-- begin of blog post  -->
                                        <div class="left-head">
                        <div class="date">24</div>
                        <div class="month">Jan</div>
                    </div>
                                        <div class="right-head">
                       <h3>An Intro to Backbone.js: Part 1 &#8211; Models and Collections</h3>       
                                                              
                       <div class="post-info">posted by : <a href="http://liquidmedia.org/author/n_time/" title="Posts by n_time" rel="author">n_time</a> &nbsp; | &nbsp; category : <a href="http://liquidmedia.org/category/blog/" title="View all posts in Blog" rel="category tag">Blog</a> &nbsp; | &nbsp; comments : <a href="http://liquidmedia.org/blog/2011/01/backbone-js-part-1/#comments" title="Comment on An Intro to Backbone.js: Part 1 &#8211; Models and Collections"><span class="dsq-postid" rel="118 http://liquidmedia.ca/?p=118">31 Comments</span></a></div>
                                           </div>
                    <div class="blog-posted">
                      <!--
                          <div class="blog-box">
                            <img src="http://liquidmedia.org/wp-content/themes/vulcan/timthumb.php?src=&amp;h=129&amp;w=223&amp;zc=1" alt="An Intro to Backbone.js: Part 1 &#8211; Models and Collections"/>
                            </div>
-->
                                                  <p><a href="http://documentcloud.github.com/backbone/"><img src="http://liquidmedia.ca/wp-content/uploads/2011/01/backbone-logo.png" alt="" title="backbone-logo" width="385" height="126" class="alignnone size-full wp-image-352" /></a></p>
<div class="notice" style="padding: 20px; margin-bottom: 20px; color: #000; background-color: #EBEBEB; border-radius: 5px; -moz-border-radius: 5px;">This is Part 1 of a series of tutorials. You can find <a href="http://liquidmedia.ca/blog/2011/01/an-intro-to-backbone-js-part-2-controllers-and-views/">Part 2 here</a>.</div>
<p>JavaScript interpreters are FAST, and they&#8217;re in every browser out there. You can run a rich application in the browser using only open technologies and built in browser-functionality, today.</p>
<p><strong><a href="http://documentcloud.github.com/backbone/">Backbone.js</a></strong> can help build it. It&#8217;s a light-weight MVC for the browser &#8211; only <a href="http://documentcloud.github.com/backbone/docs/backbone.html">~1000 lines of code</a>, and it&#8217;s <strong>clean</strong>. </p>
<p>There&#8217;s no magic. It&#8217;s mostly just a structure for the code you write &#8211; not a bulky collection of widgets and doodads. It&#8217;s fast to learn, and lets you work with whatever technologies you&#8217;re already comfortable with.</p>
<h2>Trying Out Backbone</h2>
<p>If you&#8217;re looking to try it out, you&#8217;re going to need to load <a href="http://documentcloud.github.com/underscore/">Underscore.js</a> first. It&#8217;s Backbone&#8217;s only major dependency.</p>
<p>Oh yeah, and Backbone does not have anything to do with the DOM, although it does have some loose dependencies on the $ and ajax calls of jQuery/Zepto. If you aren&#8217;t using jQuery or Zepto then you&#8217;ll need to do a little more work (<em>like 10 lines of code</em>). I&#8217;ll go over the particulars in the next post. For now, play nice and just use jQuery or Zepto if you feel like following along.</p>
<h2>What&#8217;s going on in there?</h2>
<p>There are five main prototypes in Backbone.</p>
<ul>
<li>Backbone.Collection &#8211; A little more than what you&#8217;re thinking.</li>
<li>Backbone.Model &#8211; ActiveRecord implementation, but it&#8217;s got a url!</li>
<li>Backbone.Controller &#8211; More or less exactly what you&#8217;re thinking.</li>
<li>Backbone.View &#8211; If you&#8217;re from Rails, then it&#8217;s not what you&#8217;re thinking.</li>
<li>Backbone.Events &#8211; Inherit from this guy to give your objects PubSub!</li>
</ul>
<p>In this blog post we&#8217;re going to look at <strong>Models, Collections, and Events.</strong></p>
<h3>Backbone.Model:</h3>
<p>An implementation of the ActiveRecord pattern, but using JSON and a RESTful API instead of directly interfacing with a database.</p>
<p>So let&#8217;s say that we&#8217;re working on a donut app, and we want to be able to describe our donuts!</p>
<pre class="brush: js">  // We extend the Backbone.Model prototype to build our own
  var Donut = Backbone.Model.extend({

    // We can pass it default values.
    defaults : {
      name : null,
      sparkles : false,
      cream_filled : false
    },

    url : function() {
      // Important! It's got to know where to send its REST calls. 
      // In this case, POST to '/donuts' and PUT to '/donuts/:id'
      return this.id ? '/donuts/' + this.id : '/donuts'; 
    } 

  });
</pre>
<p>That&#8217;s analogous to defining a model class in Rails. Now let&#8217;s put it through it&#8217;s paces a little.</p>
<pre class="brush: js"> 
// Instantiating
  var bostonCream = new Donut({ // attributes passed to the Donut constructor will override the defaults
    name : "Bostan Cream",
    cream_filled : true
  });

  // Updating and retrieving attributes
  // Actually, let's put sprinkles on that...
  bostonCream.set({ sprinkles : true }); 

  // Saving
  bostonCream.save(); // this will now POST to the RESTful interface.
</pre>
<p>Backbone.Model#save is an asynchronous method. So you&#8217;ll need to provide a callback. The following code assumes success.</p>
<pre class="brush: js">
  // Now that it's saved it'll have an id..
  bostonCream.id;
  -&gt; 3, or whatever number your JSON api passed up.

  // Wait, what's the name?
  bostonCream.get("name");
  -&gt; "Bostan Cream"

  // Ugh, sprinkles are gross. And there's a typo in the name.
  bostonCream.set({
    sprinkles : false,
    name : "Boston Cream"
  });

  // Updating
  bostonCream.save(); // and now it's a PUT.
  // it will put directly to "donuts/3", since that's the URI
  // of the model now.
</pre>
<h3>Backbone.Collection:</h3>
<p>A collection of models, duh. It&#8217;s a little smarter than that. It proxies to Underscore to give you a bunch of sweet list functions for working your data out, and lets you keep an eye on what your models are up to through a bunch of handy events. Plus, if you have a RESTful API you can tie them directly to a collection on your backend. Cool, right?</p>
<p>So let&#8217;s work out this donut example a little. If you want to manage a collection of donuts, we can use the same API we were working with earlier&#8230;</p>
<pre class="brush: js">  var Donuts = Backbone.Collection.extend({
    model : Donut,
    url : "/donuts"
  });

  var donuts = new Donuts;

  donuts.fetch(); // this makes a call to the server and populates the collection based on the response.</code></pre>
<p>The call to collection#fetch is asynchronous, so let&#8217;s assume this code is being run after the call is complete.</p>
<pre class="brush: js">
  donuts.at(0); -&gt; gets donuts by index.
  donuts.get(0); -&gt; gets donuts by id.
</pre>
<p>And a few examples of the Underscore iterator methods&#8230;</p>
<pre class="brush: js">
  donuts.each(function(donut) {
    console.log(donut.get("name"));
  });

  // Select donuts with names longer than 2
  donuts.select(function(donut) {
    return donut.get("name").length &gt; 2;
  });

  // Map...
  donuts.map(function(donut) {
    return donut.get("name");
  });
</pre>
<h4>Nested Collections</h4>
<p>One of the most common uses for collections is to make them nested. In this case, let&#8217;s introduce another model, the &#8220;Donut Shop&#8221; and let&#8217;s say that it has a list of Donuts that it serves.</p>
<pre class="brush: js">
  var DonutShop = Backbone.Model.extend({
    defaults : {
      name : "Untitled"
    },

    initialize : function() {
      // When you extend a Backbone.Model and give it an initialize function,
      // the function is called when you instantiate an instance of your Model.

      // The initialize function is used repeatedly in Backbone's prototypes. We'll be seeing this again
      this.donuts = new Donuts;
      this.donuts.url = 'donut_shops/' + this.id + "/donuts";
    }
  });
</pre>
<p>So now if you have an existing donut shop that has been saved to the server, you can go:</p>
<pre class="brush: js">
  donutShop.donuts.fetch();
</pre>
<h3>Backbone.Events:</h3>
<p>All of the Backbone core objects give you events to plug in to. For instance, the Collection prototype allows you to bind to &#8220;add&#8221; and &#8220;remove&#8221; events.</p>
<pre class="brush: js">
  donutShop.donuts.bind("add", function(donut) { 
    alert("added " + donut.get("name")); 
  });

  // now adding a donut will trigger the alert
  var lemonFilled = donutShop.donuts.add({ name : "Lemon Filled" }); 
</pre>
<p>Backbone provides you with the Backbone.Events object as well. So, since Underscore is a prereq of Backbone anyway, you can do fancy nonsense like this&#8230;</p>
<pre class="brush: js">var application = {};
_(application).extend(Backbone.Events);

// Now your application object has it's own events! For example.

application.bind("fun:had", function() { alert("wee!"); });
application.trigger("fun:had"); // it'll alert "wee!"
</pre>
<p>There&#8217;s part 1. Next time I&#8217;ll take you through some fun parts:</p>
<ul>
<li> Navigating using Backbone.Controllers</li>
<li>HashChange routing!</li>
<li>Creating a view</li>
<li>Tying a view to model events</li>
<li>Tying a view to a collection&#8217;s events.</li>
</ul>
<p>If you&#8217;re looking to try out Backbone, which I&#8217;m guessing you are, here are the relevant links.</p>
<ul>
<li><a href="http://documentcloud.github.com/underscore/">Underscore.js</a>.
<li><a href="http://documentcloud.github.com/backbone/">Backbone.js</a>.</li>
</li>
</ul>
                      <div class="clr"></div>
                                            <div class="clr"></div><br />
                      
<div id="disqus_thread">
                    <div id="dsq-content">


            <ul id="dsq-comments">
                    <li class="comment even thread-even depth-1" id="dsq-comment-15">
        <div id="dsq-comment-header-15" class="dsq-comment-header">
            <cite id="dsq-cite-15">
                <span id="dsq-author-user-15">frytaz</span>
            </cite>
        </div>
        <div id="dsq-comment-body-15" class="dsq-comment-body">
            <div id="dsq-comment-message-15" class="dsq-comment-message"><p>Good post, I&#8217;m going to use backbone.js on my next project! <img src='http://liquidmedia.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>
        </div>
    </li>

    </li>
    <li class="comment odd alt thread-odd thread-alt depth-1" id="dsq-comment-17">
        <div id="dsq-comment-header-17" class="dsq-comment-header">
            <cite id="dsq-cite-17">
                <span id="dsq-author-user-17">Jeremy</span>
            </cite>
        </div>
        <div id="dsq-comment-body-17" class="dsq-comment-body">
            <div id="dsq-comment-message-17" class="dsq-comment-message"><p>Terrific introduction &#8212; thanks! Slight typo in the second code block showing the examples.</p>
<p>  // Wait, what&#8217;s the name?<br />
  bostonCream.get(&#8220;name&#8221;);<br />
  -&gt; &#8220;Boston Cream&#8221;</p>
<p>should that be </p>
<p>  // Wait, what&#8217;s the name?<br />
  bostonCream.get(&#8220;name&#8221;);<br />
  -&gt; &#8220;Bostan Cream&#8221;</p>
<p>since it hasn&#8217;t been updated yet?</p>
</div>
        </div>
    </li>

    </li>
    <li class="comment byuser comment-author-n_time bypostauthor even thread-even depth-1" id="dsq-comment-18">
        <div id="dsq-comment-header-18" class="dsq-comment-header">
            <cite id="dsq-cite-18">
                <span id="dsq-author-user-18">n_time</span>
            </cite>
        </div>
        <div id="dsq-comment-body-18" class="dsq-comment-body">
            <div id="dsq-comment-message-18" class="dsq-comment-message"><p>Nice catch! Thanks for the feedback!</p>
</div>
        </div>
    </li>

    </li>
    <li class="post pingback">
        <p>Pingback: <a href='http://www.netcrema.net/?p=68382' rel='external nofollow' class='url'>An Intro to Backbone.js: Part 1 – Models and Collections &#8211; Liquid Media &laquo; Netcrema &#8211; creme de la social news via digg + delicious + stumpleupon + reddit</a></p>
    </li>
    </li>
    <li class="post pingback">
        <p>Pingback: <a href='http://toshism.com/main/2011/01/25/links-for-2011-01-25/' rel='external nofollow' class='url'>links for 2011-01-25 | toshism</a></p>
    </li>
    </li>
    <li class="comment odd alt thread-odd thread-alt depth-1" id="dsq-comment-33">
        <div id="dsq-comment-header-33" class="dsq-comment-header">
            <cite id="dsq-cite-33">
                <span id="dsq-author-user-33">Adam</span>
            </cite>
        </div>
        <div id="dsq-comment-body-33" class="dsq-comment-body">
            <div id="dsq-comment-message-33" class="dsq-comment-message"><p>Great post, can&#8217;t wait for the next one on backbone!</p>
</div>
        </div>
    </li>

    </li>
    <li class="comment even thread-even depth-1" id="dsq-comment-34">
        <div id="dsq-comment-header-34" class="dsq-comment-header">
            <cite id="dsq-cite-34">
                <span id="dsq-author-user-34">caner</span>
            </cite>
        </div>
        <div id="dsq-comment-body-34" class="dsq-comment-body">
            <div id="dsq-comment-message-34" class="dsq-comment-message"><p>thanks for the article but can you please change the font color of your code example divs. white on black background just f&#8217;d my eyes.</p>
</div>
        </div>
    </li>

    </li>
    <li class="comment odd alt thread-odd thread-alt depth-1" id="dsq-comment-36">
        <div id="dsq-comment-header-36" class="dsq-comment-header">
            <cite id="dsq-cite-36">
                <span id="dsq-author-user-36">Johan</span>
            </cite>
        </div>
        <div id="dsq-comment-body-36" class="dsq-comment-body">
            <div id="dsq-comment-message-36" class="dsq-comment-message"><p>Just starting out with backbone.js and enjoyed your nice examples and explanation. Looking forward to the next post.</p>
</div>
        </div>
    </li>

    </li>
    <li class="comment even thread-even depth-1" id="dsq-comment-39">
        <div id="dsq-comment-header-39" class="dsq-comment-header">
            <cite id="dsq-cite-39">
http://pomodoro.nl                <span id="dsq-author-user-39">pomodoro</span>
            </cite>
        </div>
        <div id="dsq-comment-body-39" class="dsq-comment-body">
            <div id="dsq-comment-message-39" class="dsq-comment-message"><p>Nice article looking forward to the next one. I&#8217;m just finishing my first project using backbone and am really enthusiastic. Especially with the clarity of the framework and great support on irc.</p>
</div>
        </div>
    </li>

    </li>
    <li class="post pingback">
        <p>Pingback: <a href='http://pietrowski.info/2011/01/pedro-newsletter-28-01-2011/' rel='external nofollow' class='url'>Pedro Newsletter 28.01.2011 &laquo; Pragmatic Programmer Issues &#8211; pietrowski.info</a></p>
    </li>
    </li>
    <li class="comment odd alt thread-odd thread-alt depth-1" id="dsq-comment-55">
        <div id="dsq-comment-header-55" class="dsq-comment-header">
            <cite id="dsq-cite-55">
http://www.redstone.eu                <span id="dsq-author-user-55">Greg</span>
            </cite>
        </div>
        <div id="dsq-comment-body-55" class="dsq-comment-body">
            <div id="dsq-comment-message-55" class="dsq-comment-message"><p>Great introduction, thanks! A little curios about the first code snippet; &#8220;url : &#8220;/donuts&#8221; // Important!&#8221; for the Donut model. Setting this to a hard coded value will not work, will it? In your second snippet, the update will PUT to &#8220;/donuts&#8221; since the url attribute will be used.</p>
<p>I think the default behavior of Backbone, given that no url attribute (which may be a function) is supplied on the model, is to use the collection url and add the ID if the model has been saved before. Setting the url on the Donut model will override this behavior and will not automatically append the ID.</p>
<p>Looking forward to the next part, Cheers!</p>
</div>
        </div>
    </li>

    <ul class='children'>
    <li class="comment byuser comment-author-n_time bypostauthor even depth-2" id="dsq-comment-59">
        <div id="dsq-comment-header-59" class="dsq-comment-header">
            <cite id="dsq-cite-59">
                <span id="dsq-author-user-59">n_time</span>
            </cite>
        </div>
        <div id="dsq-comment-body-59" class="dsq-comment-body">
            <div id="dsq-comment-message-59" class="dsq-comment-message"><p>Hi Greg,</p>
<p>Thanks for the feedback. You&#8217;re totally right.</p>
<p>It&#8217;s possible to give url a function as well, so I&#8217;ve now moved the proper behavior into the model. Nice catch!</p>
<p>In most of our projects we&#8217;ve used .add on Collections, so I hadn&#8217;t realized that was a misconception. Good thing!</p>
</div>
        </div>
    </li>

    </li>
</ul>
</li>
    <li class="post pingback">
        <p>Pingback: <a href='http://jsmag.com/blog/2011/02/news-roundup-the-performance-of-feature-detection-mobile-firefox-4-performance-w3c-touch-events/' rel='external nofollow' class='url'>JavaScript Magazine Blog for JSMag &raquo; Blog Archive &raquo; News roundup: the performance of feature detection, Mobile Firefox 4 performance, W3C Touch Events</a></p>
    </li>
    </li>
    <li class="comment odd alt thread-even depth-1" id="dsq-comment-80">
        <div id="dsq-comment-header-80" class="dsq-comment-header">
            <cite id="dsq-cite-80">
http://twitter.com/MattMueller                <span id="dsq-author-user-80">MattMueller</span>
            </cite>
        </div>
        <div id="dsq-comment-body-80" class="dsq-comment-body">
            <div id="dsq-comment-message-80" class="dsq-comment-message"><p>Great introduction! It&#8217;s worth noting that this example does not work &#8211; bostonCream.save() is an asynchronous event and will not return an id in time for bostonCream.id. Mentioning that would have saved me some time, so it may be useful to add that for others.</p>
<p>One other helpful tip is elaborating on what the &#8220;json api&#8221; returns back. You need to pass back JSON that includes { id: someID &#8230;. }</p>
<p>Thanks again!</p>
</div>
        </div>
    </li>

    <ul class='children'>
    <li class="comment even depth-2" id="dsq-comment-81">
        <div id="dsq-comment-header-81" class="dsq-comment-header">
            <cite id="dsq-cite-81">
                <span id="dsq-author-user-81">Anonymous</span>
            </cite>
        </div>
        <div id="dsq-comment-body-81" class="dsq-comment-body">
            <div id="dsq-comment-message-81" class="dsq-comment-message"><p>Hey man! Thanks for the feedback! I&#8217;ve included mention of this above. <img src='http://liquidmedia.org/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
</div>
        </div>
    </li>

    </li>
    <li class="comment odd alt depth-2" id="dsq-comment-114">
        <div id="dsq-comment-header-114" class="dsq-comment-header">
            <cite id="dsq-cite-114">
http://profiles.yahoo.com/u/V7LGTBIAONDXFOC4A7LRH6LD7U                <span id="dsq-author-user-114">George</span>
            </cite>
        </div>
        <div id="dsq-comment-body-114" class="dsq-comment-body">
            <div id="dsq-comment-message-114" class="dsq-comment-message"><p>The parse method of the model can be overridden to handle JSON that is not exactly formatted the way JSON needs.  For example, I work with a legacy api and all the data I need comes back in a nested property called data.  In the parse method I can just do the following: </p>
<p> parse: function (response)<br />
    {<br />
        return {<br />
            id: response.data.id,<br />
            version: response.data.version,<br />
            name: response.data.name,<br />
            key: response.data.key,<br />
           etc..<br />
        };</p>
<p>    },</p>
</div>
        </div>
    </li>

    </li>
    <li class="comment even depth-2" id="dsq-comment-169">
        <div id="dsq-comment-header-169" class="dsq-comment-header">
            <cite id="dsq-cite-169">
                <span id="dsq-author-user-169">iJames</span>
            </cite>
        </div>
        <div id="dsq-comment-body-169" class="dsq-comment-body">
            <div id="dsq-comment-message-169" class="dsq-comment-message"><p>Your comment about JSON needint {id: something&#8230;} is the most crucial thing I&#8217;ve seen anywhere regarding backbone.  The concept of backbone is awesome but I have spent way too long trying to decipher exactly what the JSON can look like and how to render that&#8230;  Thanks for this little winner!!!</p>
</div>
        </div>
    </li>

    </li>
</ul>
</li>
    <li class="post pingback">
        <p>Pingback: <a href='http://www.quora.com/What-are-some-good-resources-for-Backbone-js#ans428529' rel='external nofollow' class='url'>Quora</a></p>
    </li>
    </li>
    <li class="comment odd alt thread-odd thread-alt depth-1" id="dsq-comment-108">
        <div id="dsq-comment-header-108" class="dsq-comment-header">
            <cite id="dsq-cite-108">
                <span id="dsq-author-user-108">Steveshamen</span>
            </cite>
        </div>
        <div id="dsq-comment-body-108" class="dsq-comment-body">
            <div id="dsq-comment-message-108" class="dsq-comment-message"><p>This example is complicated. </p>
<p>Where is the start, middle and end. Currently all I see is the middle. Where is the page load initiator? Ie document onready/ window.onload etc..</p>
<p>What does the default html and end result look like on the page?</p>
<p>I can assume only so much when all I&#8217;m looking at is clever object structures extended using an unknown library (backbone) with jquery. </p>
<p>I am stupid. Don&#8217;t miss out the essential. I want to see the most basic of examples working and examples of why this id superior to say doing?</p>
<p>//JS ###################<br />
//includes/depends: jquery, backbone etc&#8230;</p>
<p>//libary<br />
function parse(xml){<br />
//parse xml etc&#8230;<br />
return xml;<br />
}</p>
<p>//onload<br />
$(function(){<br />
$.ajax(url,function(xml){<br />
$(&#8216;#liveupdate&#8217;).html(parse(xml));<br />
})<br />
})</p>
<p>//DEFAULT HTML #############################<br />
loading&#8230;</p>
<p>//RESULT HTML ###############################<br />
content from the url has been loaded into this div.</p>
</div>
        </div>
    </li>

    </li>
    <li class="post pingback">
        <p>Pingback: <a href='http://www.kickasslabs.com/2011/04/16/yet-another-backbone-js-tutorial-part-1-backbone-js-philosophy/' rel='external nofollow' class='url'>Kickass Labs &raquo; Blog Archive &raquo; Yet Another Backbone.js Tutorial &#8211; Part 1 &#8211; Backbone.js Philosophy</a></p>
    </li>
    </li>
    <li class="comment even thread-even depth-1" id="dsq-comment-132">
        <div id="dsq-comment-header-132" class="dsq-comment-header">
            <cite id="dsq-cite-132">
                <span id="dsq-author-user-132">Diegocastorina</span>
            </cite>
        </div>
        <div id="dsq-comment-body-132" class="dsq-comment-body">
            <div id="dsq-comment-message-132" class="dsq-comment-message"><p>I also wrote something about Backbone.</p>
<p><a href="http://a-developer-life.blogspot.com/2011/04/backbone-part-1-intro-and-model.html" rel="nofollow">http://a-developer-life.blogspot.com/2011/04/backbone-part-1-intro-and-model.html</a></p>
<p><a href="http://a-developer-life.blogspot.com/2011/04/backbone-part-2-view-and-controller.html" rel="nofollow">http://a-developer-life.blogspot.com/2011/04/backbone-part-2-view-and-controller.html</a></p>
</div>
        </div>
    </li>

    </li>
    <li class="comment odd alt thread-odd thread-alt depth-1" id="dsq-comment-146">
        <div id="dsq-comment-header-146" class="dsq-comment-header">
            <cite id="dsq-cite-146">
                <span id="dsq-author-user-146">Jacek</span>
            </cite>
        </div>
        <div id="dsq-comment-body-146" class="dsq-comment-body">
            <div id="dsq-comment-message-146" class="dsq-comment-message"><p>Links for other two parts are needed&#8230; Now only place to find those is google.<br />
Very good tutorial though (all 3 parts)</p>
</div>
        </div>
    </li>

    </li>
    <li class="post pingback">
        <p>Pingback: <a href='http://jasonbutz.info/2011/07/jquery-backbone-js/' rel='external nofollow' class='url'>jQuery &amp; Backbone.js | IT Zen</a></p>
    </li>
    </li>
    <li class="comment even thread-even depth-1" id="dsq-comment-159">
        <div id="dsq-comment-header-159" class="dsq-comment-header">
            <cite id="dsq-cite-159">
                <span id="dsq-author-user-159">Stephen</span>
            </cite>
        </div>
        <div id="dsq-comment-body-159" class="dsq-comment-body">
            <div id="dsq-comment-message-159" class="dsq-comment-message"><p>first found this set of tutorials 5 months ago, and found it to be a great introduction, but I haven&#8217;t really had need to leverage backbone in the interim.  Now i&#8217;m diving into it much more deeply and I&#8217;ve once again come back to this tutorial!  The nested collection, in particular the method for supporting its url was EXACTLY what I was looking for confirmation on.</p>
<p>THANK YOU!</p>
</div>
        </div>
    </li>

    </li>
    <li class="comment odd alt thread-odd thread-alt depth-1" id="dsq-comment-212">
        <div id="dsq-comment-header-212" class="dsq-comment-header">
            <cite id="dsq-cite-212">
                <span id="dsq-author-user-212">yun_cn</span>
            </cite>
        </div>
        <div id="dsq-comment-body-212" class="dsq-comment-body">
            <div id="dsq-comment-message-212" class="dsq-comment-message"><p>if you had added  executable examples that might help me a lot as an introduction.</p>
</div>
        </div>
    </li>

    </li>
    <li class="comment even thread-even depth-1" id="dsq-comment-238">
        <div id="dsq-comment-header-238" class="dsq-comment-header">
            <cite id="dsq-cite-238">
                <span id="dsq-author-user-238">Max</span>
            </cite>
        </div>
        <div id="dsq-comment-body-238" class="dsq-comment-body">
            <div id="dsq-comment-message-238" class="dsq-comment-message"><p>It would be great if you could tie up some loose ends in this tutorial. Where is the &#8220;Donut&#8221; class created? You new it, but you don&#8217;t seem to define it anywhere.</p>
</div>
        </div>
    </li>

    </li>
    <li class="post pingback">
        <p>Pingback: <a href='http://rubysource.com/loccasions-going-client-side-with-leaflet-backbone-and-jasmine/' rel='external nofollow' class='url'>Loccasions: Going Client-Side with Leaflet, Backbone, and Jasmine » RubySource</a></p>
    </li>
    </li>
    <li class="comment odd alt thread-odd thread-alt depth-1" id="dsq-comment-305">
        <div id="dsq-comment-header-305" class="dsq-comment-header">
            <cite id="dsq-cite-305">
                <span id="dsq-author-user-305">Murali Rama Krishnan</span>
            </cite>
        </div>
        <div id="dsq-comment-body-305" class="dsq-comment-body">
            <div id="dsq-comment-message-305" class="dsq-comment-message"><p>donuts.pluck(&#8216;name&#8217;)easier way to map the collections</p>
</div>
        </div>
    </li>

    </li>
    <li class="comment even thread-even depth-1" id="dsq-comment-380">
        <div id="dsq-comment-header-380" class="dsq-comment-header">
            <cite id="dsq-cite-380">
                <span id="dsq-author-user-380">Jiggaboo</span>
            </cite>
        </div>
        <div id="dsq-comment-body-380" class="dsq-comment-body">
            <div id="dsq-comment-message-380" class="dsq-comment-message"><p>Very bad tutorial. You should delete it to not waste time of people that try to learn Backbone.</p>
</div>
        </div>
    </li>

    </li>
    <li class="comment odd alt thread-odd thread-alt depth-1" id="dsq-comment-392">
        <div id="dsq-comment-header-392" class="dsq-comment-header">
            <cite id="dsq-cite-392">
http://twitter.com/davearel                <span id="dsq-author-user-392">David Arel</span>
            </cite>
        </div>
        <div id="dsq-comment-body-392" class="dsq-comment-body">
            <div id="dsq-comment-message-392" class="dsq-comment-message"><p>FYI, you have &#8220;sparkles&#8221; instead of &#8220;sprinkles&#8221; within your defaults object.</p>
</div>
        </div>
    </li>

    </li>
    <li class="comment even thread-even depth-1" id="dsq-comment-459">
        <div id="dsq-comment-header-459" class="dsq-comment-header">
            <cite id="dsq-cite-459">
                <span id="dsq-author-user-459">Prajwol</span>
            </cite>
        </div>
        <div id="dsq-comment-body-459" class="dsq-comment-body">
            <div id="dsq-comment-message-459" class="dsq-comment-message"><p>Indeed, &#8220;This example is complicated.&#8221;<br />
If only you could provide us the executable files with the possible outcomes. Im finding it hard to even start.<br />
Cud you please explain about that url part like what does it do and why we need it?</p>
</div>
        </div>
    </li>

    </li>
            </ul>


        </div>

    </div>

<script type="text/javascript">
/* <![CDATA[ */
    var disqus_url = 'http://liquidmedia.org/blog/2011/01/backbone-js-part-1/';
    var disqus_identifier = '118 http://liquidmedia.ca/?p=118';
    var disqus_container_id = 'disqus_thread';
    var disqus_domain = 'disqus.com';
    var disqus_shortname = 'liquidmediaca';
    var disqus_title = "An Intro to Backbone.js: Part 1 &#8211; Models and Collections";
        var disqus_config = function () {
        var config = this; // Access to the config object

        /*
           All currently supported events:
            * preData — fires just before we request for initial data
            * preInit - fires after we get initial data but before we load any dependencies
            * onInit  - fires when all dependencies are resolved but before dtpl template is rendered
            * afterRender - fires when template is rendered but before we show it
            * onReady - everything is done
         */

        config.callbacks.preData.push(function() {
            // clear out the container (its filled for SEO/legacy purposes)
            document.getElementById(disqus_container_id).innerHTML = '';
        });
                config.callbacks.onReady.push(function() {
            // sync comments in the background so we don't block the page
            var script = document.createElement('script');
            script.async = true;
            script.src = '?cf_action=sync_comments&post_id=118';

            var firstScript = document.getElementsByTagName( "script" )[0];
            firstScript.parentNode.insertBefore(script, firstScript);
        });
                    };
    var facebookXdReceiverPath = 'http://liquidmedia.org/wp-content/plugins/disqus-comment-system/xd_receiver.htm';
/* ]]> */
</script>

<script type="text/javascript">
/* <![CDATA[ */
    var DsqLocal = {
        'trackbacks': [
            {
                'author_name':    "An Intro to Backbone.js: Part 1 – Models and Collections &#8211; Liquid Media &laquo; Netcrema &#8211; creme de la social news via digg + delicious + stumpleupon + reddit",
                'author_url':    "http:\/\/www.netcrema.net\/?p=68382",
                'date':            "01\/25\/2011 08:19 PM",
                'excerpt':        "[...] An Intro to Backbone.js: Part 1 – Models and Collections &#8211; Liquid Medialiquidmedia.ca [...] ",
                'type':            "pingback"            }
,            {
                'author_name':    "links for 2011-01-25 | toshism",
                'author_url':    "http:\/\/toshism.com\/main\/2011\/01\/25\/links-for-2011-01-25\/",
                'date':            "01\/26\/2011 12:02 AM",
                'excerpt':        "[...] An Intro to Backbone.js: Part 1 – Models and Collections &#8211; Liquid Media (tags: backbone.js javascript programming webdev)  ...",
                'type':            "pingback"            }
,            {
                'author_name':    "Pedro Newsletter 28.01.2011 &laquo; Pragmatic Programmer Issues &#8211; pietrowski.info",
                'author_url':    "http:\/\/pietrowski.info\/2011\/01\/pedro-newsletter-28-01-2011\/",
                'date':            "01\/28\/2011 12:05 AM",
                'excerpt':        "[...] introduction part 1: Models and Collections, part 2: Controllers and [...] ",
                'type':            "pingback"            }
,            {
                'author_name':    "JavaScript Magazine Blog for JSMag &raquo; Blog Archive &raquo; News roundup: the performance of feature detection, Mobile Firefox 4 performance, W3C Touch Events",
                'author_url':    "http:\/\/jsmag.com\/blog\/2011\/02\/news-roundup-the-performance-of-feature-detection-mobile-firefox-4-performance-w3c-touch-events\/",
                'date':            "02\/04\/2011 04:47 PM",
                'excerpt':        "[...] and apps (Google Chrome Blog) Game On Winners: Level Up the Open Web (Mozilla Labs) AwesomeChartJS An Intro to ...",
                'type':            "pingback"            }
,            {
                'author_name':    "Quora",
                'author_url':    "http:\/\/www.quora.com\/What-are-some-good-resources-for-Backbone-js#ans428529",
                'date':            "03\/07\/2011 04:33 PM",
                'excerpt':        "What are some good resources for Backbone.js?...<br \/><br \/>Official Backbone.js Resources * http:\/\/documentcloud.github.com\/backbone\/ * http:\/\/documentcloud.github.com\/underscore\/ (Backbone.js hard dependency) Startups\/Apps Built on Backbone.js ...",
                'type':            "trackback"            }
,            {
                'author_name':    "Kickass Labs &raquo; Blog Archive &raquo; Yet Another Backbone.js Tutorial &#8211; Part 1 &#8211; Backbone.js Philosophy",
                'author_url':    "http:\/\/www.kickasslabs.com\/2011\/04\/16\/yet-another-backbone-js-tutorial-part-1-backbone-js-philosophy\/",
                'date':            "04\/16\/2011 11:18 PM",
                'excerpt':        "[...] Liquid Media&#8217;s backbone tutorial (3 parts) [...] ",
                'type':            "pingback"            }
,            {
                'author_name':    "jQuery &amp; Backbone.js | IT Zen",
                'author_url':    "http:\/\/jasonbutz.info\/2011\/07\/jquery-backbone-js\/",
                'date':            "07\/27\/2011 06:20 PM",
                'excerpt':        "[...] found a tutorial at Liquid Media very helpful when I was just getting started. I also suggest using the ...",
                'type':            "pingback"            }
,            {
                'author_name':    "Loccasions: Going Client-Side with Leaflet, Backbone, and Jasmine » RubySource",
                'author_url':    "http:\/\/rubysource.com\/loccasions-going-client-side-with-leaflet-backbone-and-jasmine\/",
                'date':            "11\/30\/2011 10:30 AM",
                'excerpt':        "[...] my wife cutting the power to my office.).Also, I won&#8217;t cover the basics of Backbone, as that has been ...",
                'type':            "pingback"            }
        ],
        'trackback_url': "http:\/\/liquidmedia.org\/blog\/2011\/01\/backbone-js-part-1\/trackback\/"    };
/* ]]> */
</script>

<script type="text/javascript">
/* <![CDATA[ */
(function() {
    var dsq = document.createElement('script'); dsq.type = 'text/javascript';
    dsq.async = true;
        dsq.src = 'http' + '://' + disqus_shortname + '.' + 'disqus.com' + '/embed.js?pname=wordpress&pver=2.73';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
/* ]]> */
</script>
                                         
                    </div>                
                                     
                </div>
            </div>
                                          <div id="content-right">
            	<!-- begin of sidebar -->
                          	
                              
                <!-- end of sidebar -->
                
                <div class="sidebar">
    <div id="twCard">
      <h3>Author:</h3>
       
      <div class="mainCard">
        <img class="userPic" src="http://liquidmedia.org/wp-content/themes/vulcan/timthumb.php?src=&h=60&w=60&zc=1" alt="Neal Stewart" align=top> 
        <div class="twInnerBox">          
          <div>
            <h6>@</h6>
            <p>--</p>
            <hr>
          </div>
          <a class="tw" href="http://twitter.com/#!/">twitter</a>
          <a class="gh" href="https://github.com/">github</a>
        </div>          
      </div>
      <div class="drawer">
        <h2>@LiquidMedia</h2>
        <a class="tw" href="http://twitter.com/#!/liquidmediaca">twitter</a>
          <a class="gh" href="https://github.com/liquidmedia">github</a>
      </div>
    </div>
</div>
<div class="sidebar-bottom">
</div>

	<div class="sidebar"><h3>Latest News</h3>    <ul class="itemlist">
        <li><a href="http://liquidmedia.org/news/2011/09/were-moving-on-october-1/">We&#8217;re moving on October 1 <strong>21 September 2011</strong></a></li>
       <li><a href="http://liquidmedia.org/news/2011/02/hacksat-26-feb/">Next hacks@ on Saturday 26 February at 4:30 p.m. <strong>14 February 2011</strong></a></li>
       <li><a href="http://liquidmedia.org/news/2011/01/urtak-facebook-app-launches/">Urtak Facebook App launches <strong>15 January 2011</strong></a></li>
      </ul>
   </div><div class="sidebar-bottom"></div><div class="sidebar">			<div class="textwidget"><h3>The Urtak Widget</h3>
<h5>A Liquid Media solution.</h5>
<br />
<script src="http://assets.urtak.com/javascripts/widget.js" type="text/javascript"></script>
<a data-urtak-widget-key="l9zo3izpjyoqvhudrgr8q6kjq5ijxy79" href="http://urtak.com/u/5092">Liquid Media</a>
<br/>

<p><a href="/portfolio/urtak">Read more about Liquid Media’s work for Urtak.com</a>.</p></div>
		</div><div class="sidebar-bottom"></div> 
            </div>                
                          
        </div>
        <!-- END OF CONTENT -->
                <!-- BEGIN OF FOOTER -->
        <div id="bottom-container">
        	<div id="footer-content">
            
            	<!-- begin of footer-address --> 
            	<div id="footer-address">
                                <img src="http://liquidmedia.org/wp-includes/images/logo_white.png "  alt="Liquid Media" />
                <p>400-1668 Barrington St.<br/>
Halifax NS   B3J 2A2

</p>
                <p>Phone : 902-412-2492<br>Fax : 902-482-5014<br/>Email : info@liquidmedia.org</p>
                </div>
                <!-- end of footer-address -->
                
                <div id="footer-news">
                                <h3><a href="/news">Company News</a></h3>
                    <ul class="list-bottom">
                                    <!-- begin of company-news -->
                                                 
                    <li><a href="http://liquidmedia.org/news/2011/09/were-moving-on-october-1/">We&#8217;re moving on October 1 - <strong>21 September 2011</strong></a></li>
                                                 
                    <li><a href="http://liquidmedia.org/news/2011/02/hacksat-26-feb/">Next hacks@ on Saturday 26 February at 4:30 p.m. - <strong>14 February 2011</strong></a></li>
                                                 
                    <li><a href="http://liquidmedia.org/news/2011/01/urtak-facebook-app-launches/">Urtak Facebook App launches - <strong>15 January 2011</strong></a></li>
                                                 
                    <li><a href="http://liquidmedia.org/news/2011/01/new-swankier-office/">New, swankier, office! - <strong>02 January 2011</strong></a></li>
                    
                <!-- end of company-news -->
                  </ul>
                                </div>                
                <!-- begin of footer-menu and copyright -->
                <div id="footer-last">
                	<div id="footer-menu">
                  	<ul class="navigation-footer">
  	<li ><a href="http://liquidmedia.org">Home</a></li>
  	<li class="page_item page-item-2"><a href="http://liquidmedia.org/software_application_developer/">About</a></li>
<li class="page_item page-item-15"><a href="http://liquidmedia.org/portfolio/">Portfolio</a></li>
<li class="page_item page-item-17"><a href="http://liquidmedia.org/contact/">Contact</a></li>
<li class="page_item page-item-81"><a href="http://liquidmedia.org/solutions/">Solutions</a></li>
<li class="page_item page-item-207"><a href="http://liquidmedia.org/blog/">Blog</a></li>
  </ul>

                    </div>
                    <div id="footer-copyright">
                                        Copyright © 2010-2012                    </div>
                </div>
                <!-- end of footer-menu and copyright -->
                            
            </div>
        </div>
        <!-- END OF FOOTER -->
    	
    </div>
    <script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-20103121-1']);
  _gaq.push(['_setDomainName', '.liquidmedia.ca']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>    <script>
      SyntaxHighlighter.all();
    </script>
    </body>
</html>
